package com.zhu.storesmanager.network;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import com.zhu.storesmanager.R;
import com.zhu.storesmanager.SvStoreCompeteActivity;
import com.zhu.storesmanager.models.SyncModel;
import com.zhu.storesmanager.models.SyncModel.DataVisitContentCompetitor;
import com.zhu.storesmanager.provider.StoresManagerSettings;
import com.zhu.storesmanager.security.DesUtil;
import com.zhu.storesmanager.utils.Base64Coder;
import com.zhu.storesmanager.utils.DataUtils;
import com.zhu.storesmanager.utils.Log;
import com.zhu.storesmanager.utils.SalesData;
import com.zhu.storesmanager.views.BrandInfoView;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

/**
 * 督导需要上传的数据类
 */
public class SupervisorData {

	private final String STOREID = "sStoreID";
	private int mVisitId = -1; //拜访任务ID －1则获取所有拜访任务
	private Context mContext = null; //上下文
	private List<VisitItem> mVisitList = new ArrayList<VisitItem>(); //拜访集合
	private List<SyncModel.VisitCheckRequest> mVisitCheckRequestList = null;//拜访任务数据集合
	private List<SyncModel.VisitContentReqeust> mVisitContentList = null;//拜访内容数据集合
	SimpleDateFormat mDateFormatMonth = new SimpleDateFormat("yyyyMM");
	private String mWhere = "";

	public SupervisorData(Context context, int visitId){
		mContext = context;
		mVisitId = visitId;
	}

	/**
	 * 开始解析获取所有数据
	 */
	public void parseData(){
		resetData();
		pasreVisitCheckData();
		pasreVisitContentData();
	}

	/**
	 * 重置数据
	 */
	public void resetData(){
		mWhere = "";
		if(mVisitContentList != null){
			mVisitContentList.clear();
			mVisitContentList = null;
		}
		if(mVisitList != null){
			mVisitList.clear();
		}
		if(mVisitCheckRequestList != null){
			mVisitCheckRequestList.clear();
			mVisitCheckRequestList = null;
		}
	}

	//获取拜访任务信息数据
	private void pasreVisitCheckData(){
		String where = null;
		if(mVisitId != -1){ //单个拜访上传
			where = StoresManagerSettings.SupervisorVisitTaskColumns.VISITID +"=" + mVisitId + " AND " +
			StoresManagerSettings.SupervisorVisitTaskColumns.PUTSTATUS +"=0";
		}else{
			where = StoresManagerSettings.SupervisorVisitTaskColumns.PUTSTATUS +"=0"; //没有上传成功的数据
		}
		Cursor cursor = mContext.getContentResolver().query(StoresManagerSettings.SupervisorVisitTaskColumns.CONTENT_URI_NO_NOTIFICATION, null,
				where, null, null);
		try {
			//数据库数据index
			final int visitIdIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorVisitTaskColumns.VISITID);
			final int storeIdIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorVisitTaskColumns.STOREID);
			final int checkInTimeIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorVisitTaskColumns.CHECKIN_TIME);
			final int checkInTimeStatusIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorVisitTaskColumns.CHECKIN_TIME_STATUS);
			final int checkInLatIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorVisitTaskColumns.CHECKIN_LAT);
			final int checkInLngIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorVisitTaskColumns.CHECKIN_LNG);
			final int checkOutTimeIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorVisitTaskColumns.CHECKOUT_TIME);
			final int checkOutTimeStatusIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorVisitTaskColumns.CHECKOUT_TIME_STATUS);
			final int checkOutLatIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorVisitTaskColumns.CHECKOUT_LAT);
			final int checkOutLngIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorVisitTaskColumns.CHECKOUT_LNG);
		
			mVisitCheckRequestList = new ArrayList<SyncModel.VisitCheckRequest>();
			while (cursor.moveToNext()) { //遍历所有数据
				//拜访数据信息
				SyncModel.VisitCheckRequest item = new SyncModel.VisitCheckRequest();
				item.Uuid = DataUtils.mUserData.mUuid;
				item.VisitId = cursor.getInt(visitIdIndex);
				item.CheckInTime = new Date(cursor.getLong(checkInTimeIndex));
				item.CheckInStatus = cursor.getString(checkInTimeStatusIndex);
				item.CheckInLongitude = cursor.getDouble(checkInLngIndex);
				item.CheckInLatitude = cursor.getDouble(checkInLatIndex);
				long coutTime = cursor.getLong(checkOutTimeIndex);
				item.CheckOutTime = new Date(coutTime);
				item.CheckOutStatus = cursor.getString(checkOutTimeStatusIndex);
				item.CheckOutLongitude = cursor.getDouble(checkOutLngIndex);
				item.CheckOutLatitude =  cursor.getDouble(checkOutLatIndex);
				item.MobileTime = new Date();
				if(coutTime > 1){ //只有签出的数据才上传
					mVisitCheckRequestList.add(item); //添加至集合

					VisitItem visitItem = new VisitItem(); //保存上传了的数据信息
					visitItem.visitId = item.VisitId;
					visitItem.mStoreId = cursor.getString(storeIdIndex);
					mVisitList.add(visitItem);
					if(mWhere.length() < 1){
						mWhere = STOREID + "=\'" + visitItem.mStoreId +"\' AND " + StoresManagerSettings.SAVED +"=0";
					}else{
						mWhere += " OR " + STOREID + "=\'" + visitItem.mStoreId +"\' AND " + StoresManagerSettings.SAVED +"=0";
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			Log.e("pasreVisitCheckData error");
		}finally{
			if(cursor != null){
				cursor.close();
				cursor = null;
			}
		}
	}

	/**
	 * 获取拜访内容接口
	 */
	private void pasreVisitContentData(){
        if(mWhere.length() > 1){
        	mVisitContentList = new ArrayList<SyncModel.VisitContentReqeust>();
        	getSampleData();
        	getBoothData();
        	getSalesData();
        	getPOSMData();
        	getCompeteData();
        	getPromoterInfoData();
        	getSpecialTaskData();
        }
	}

	/**
	 * 获取出样数据
	 */
	private void getSampleData(){
		Cursor cursor = mContext.getContentResolver().query(StoresManagerSettings.SupervisorStoreSampleColumns.CONTENT_URI_NO_NOTIFICATION, null,
				mWhere, null, null);
		try {
			//数据库数据index
			final int storeIdIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStoreSampleColumns.STOREID);
			final int countIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStoreSampleColumns.SAMPLE_COUNT);
			final int nonecountIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStoreSampleColumns.NONESAMPLE_COUNT);
			final int thememodelsIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStoreSampleColumns.THEME_MODELS);
			final int timemodelsIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStoreSampleColumns.TIME_MODELS);
			final int othermodelsIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStoreSampleColumns.OTHER_MODELS);
			final int digitIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStoreSampleColumns.DIGIT_DEMO);
		
			while (cursor.moveToNext()) { //遍历所有数据
				//出样数据信息
				String storeId = cursor.getString(storeIdIndex);
			    int visitId = getVisitId(storeId);
			    if(visitId != -1){
			    	SyncModel.VisitContentReqeust visitContentReqeust = getVisitContentReqeust(visitId);
			    	visitContentReqeust.Data.SampleDisplayNum = cursor.getInt(countIndex);  //样机出样数量
			    	visitContentReqeust.Data.SampleEmptyNum = cursor.getInt(nonecountIndex); //样机空样数量
			    	visitContentReqeust.Data.ThemeModels = getModelsList(cursor.getString(thememodelsIndex));		//主题形象墙出样型号
			    	visitContentReqeust.Data.OvercolorModels = getModelsList(cursor.getString(timemodelsIndex));	//流光溢彩墙型号
			    	visitContentReqeust.Data.OtherModels = getModelsList(cursor.getString(othermodelsIndex));		//其他出样型号
			    	String demo = cursor.getString(digitIndex);
			    	if(demo != null && demo.length() > 0){
			    		String demos[] = demo.split(DataUtils.SPLIT_ROW);
				    	visitContentReqeust.Data.DemoDigitalStream = demos[0] + "," + demos[1];
			    	}
			    }
			}
		}catch(Exception e){
			e.printStackTrace();
			Log.e("getSampleData error");
		}finally{
			if(cursor != null){
				cursor.close();
				cursor = null;
			}
		}
	}

	/**
	 * 获取展台数据
	 */
	private void getBoothData(){
		Cursor cursor = mContext.getContentResolver().query(StoresManagerSettings.SupervisorStoreBoothColumns.CONTENT_URI_NO_NOTIFICATION, null,
				mWhere, null, null);
		try {
			//数据库数据index
			final int storeIdIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStoreBoothColumns.STOREID);
			final int shapeIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStoreBoothColumns.BOOTH_SHAPETEXT);
			final int infoIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStoreBoothColumns.BOOTH_INFOTEXT);
			final int baditemsIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStoreBoothColumns.BOOTH_BADITEMSTEXT);
			final int badcompleteIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStoreBoothColumns.BOOTH_BADCOMPLETE);
			final int dataIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStoreBoothColumns.BOOTH_BADDATE);
			final int connectIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStoreBoothColumns.BOOTH_CONNECTIONTEXT);
			final int photoallIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStoreBoothColumns.BOOTH_PHOTOALL);
			final int photofrontIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStoreBoothColumns.BOOTH_PHOTOFRONT);
			final int phototimeIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStoreBoothColumns.BOOTH_PHOTOTIME);
		
			while (cursor.moveToNext()) { //遍历所有数据
				//出样数据信息
				String storeId = cursor.getString(storeIdIndex);
			    int visitId = getVisitId(storeId);
			    if(visitId != -1){
			    	SyncModel.VisitContentReqeust visitContentReqeust = getVisitContentReqeust(visitId);
			    	visitContentReqeust.Data.BoothsShape = cursor.getString(shapeIndex);             //展台形状
			    	visitContentReqeust.Data.BoothsLocation = cursor.getString(infoIndex);          //展台信息
			    	visitContentReqeust.Data.BoothsBreakageItem = cursor.getString(baditemsIndex);      //展台破损项目
			    	visitContentReqeust.Data.BoothsBreakageDate = getData(cursor.getLong(dataIndex));   //展台破损日期
			    	visitContentReqeust.Data.BoothsBreakageStatus = getBoothsBreakageStatus(cursor.getInt(badcompleteIndex));    //展台破损是否完工
			    	visitContentReqeust.Data.WireExposed = cursor.getString(connectIndex);       //连线是否外露
			    	visitContentReqeust.Data.BoothsView = getBase64CoderData(cursor.getBlob(photoallIndex));  //展台全景(照片)
			    	visitContentReqeust.Data.BoothsFacade =  getBase64CoderData(cursor.getBlob(photofrontIndex)); //展台正面(照片)
			    	visitContentReqeust.Data.BoothsOvercolor = getBase64CoderData(cursor.getBlob(phototimeIndex));//展台流光溢彩墙(照片)
			    }
			}
		}catch(Exception e){
			e.printStackTrace();
			Log.e("getBoothData error");
		}finally{
			if(cursor != null){
				cursor.close();
				cursor = null;
			}
		}
	}

	/**
	 * 获取销售数据
	 */
	private void getSalesData(){
		Cursor cursor = mContext.getContentResolver().query(StoresManagerSettings.SupervisorStoreSalesColumns.CONTENT_URI_NO_NOTIFICATION, null,
				mWhere, null, null);
		try {
			//数据库数据index
			final int storeIdIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStoreSalesColumns.STOREID);
			final int dateIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStoreSalesColumns.SALES_DATE);
			final int allcountIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStoreSalesColumns.SALES_ALLCOUNT);
			final int allmoneyIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStoreSalesColumns.SALES_ALLMONEY);
			final int brandsIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStoreSalesColumns.SALES_BRANDS);
			final int collectIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStoreSalesColumns.SALES_COLLECT);
			final int checkIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStoreSalesColumns.SALES_CHECK);
			final int stockIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStoreSalesColumns.SALES_STOCK);
			final int addmodelIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStoreSalesColumns.SALES_ADDMODELS);
		
			while (cursor.moveToNext()) { //遍历所有数据
				//出样数据信息
				String storeId = cursor.getString(storeIdIndex);
			    int visitId = getVisitId(storeId);
			    if(visitId != -1){
			    	SyncModel.VisitContentReqeust visitContentReqeust = getVisitContentReqeust(visitId);

			    	SyncModel.DesDataVisitContentSales sales = new SyncModel.DesDataVisitContentSales();
			    	sales.SaleMonth = mDateFormatMonth.format(cursor.getLong(dateIndex)); //销售年月
			    	sales.SaleNum = cursor.getInt(allcountIndex);    //总销量
			    	sales.SaleAmount = cursor.getInt(allmoneyIndex); //总金额
			    	sales.Sales = BrandInfoView.getBrandData(cursor.getString(brandsIndex));   //品牌销售
			    	String salesJson = HttpUtil.getPutSalesContent(sales);
			    	visitContentReqeust.Data.SalesDes = DesUtil.des3EncodeECB2(HttpUtil.mDesKey, salesJson);
			    	sales = null;
			    	/*visitContentReqeust.Data.SaleMonth = mDateFormatMonth.format(cursor.getLong(dateIndex)); //日期
			    	visitContentReqeust.Data.SaleNum = cursor.getInt(allcountIndex);     //总销量
			    	visitContentReqeust.Data.SaleAmount = cursor.getInt(allmoneyIndex); //总金额
			    	visitContentReqeust.Data.Sales = BrandInfoView.getBrandData(cursor.getString(brandsIndex));   //品牌销售*/
			    	visitContentReqeust.Data.LedgerGatherStatus = getBoothsBreakageStatus(cursor.getInt(collectIndex));      //台账收集成功:是或否
			    	visitContentReqeust.Data.LedgerCheckStatus = getBoothsBreakageStatus(cursor.getInt(checkIndex));       //台账核对无误:是或否
			    	visitContentReqeust.Data.CounterStockStatus = getStockStatus(cursor.getInt(stockIndex));      //门店库存情况:充足或缺乏
			    	visitContentReqeust.Data.OutOfStockModels = getModelsList(cursor.getString(addmodelIndex));//缺货型号
			    }
			}
		}catch(Exception e){
			e.printStackTrace();
			Log.e("getSalesData error");
		}finally{
			if(cursor != null){
				cursor.close();
				cursor = null;
			}
		}
	}

	/**
	 * 获取POSM数据
	 */
	private void getPOSMData(){
		Cursor cursor = mContext.getContentResolver().query(StoresManagerSettings.SupervisorStorePOSMColumns.CONTENT_URI_NO_NOTIFICATION, null,
				mWhere, null, null);
		try {
			//数据库数据index
			final int storeIdIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePOSMColumns.STOREID);
			final int cornerIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePOSMColumns.POSM_PCORNER);
			final int posterIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePOSMColumns.POSM_POSTER);
			final int pageIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePOSMColumns.POSM_SINGLEPAGE);
			final int standIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePOSMColumns.POSM_STAND);
			final int errorIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePOSMColumns.POSM_ERRORINFO);
			final int backupText1Index = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePOSMColumns.POSM_BACKUPTEXT1);
			final int backupText2Index = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePOSMColumns.POSM_BACKUPTEXT2);
			final int backup1Index = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePOSMColumns.POSM_BACKUP1);
			final int backup2Index = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePOSMColumns.POSM_BACKUP2);
		
			while (cursor.moveToNext()) { //遍历所有数据
				//出样数据信息
				String storeId = cursor.getString(storeIdIndex);
			    int visitId = getVisitId(storeId);
			    if(visitId != -1){
			    	SyncModel.VisitContentReqeust visitContentReqeust = getVisitContentReqeust(visitId);
			    	visitContentReqeust.Data.SampleCornerPost = getPOSMStatus(cursor.getInt(cornerIndex)); //样机角贴:齐, 缺,破损,不允许
			    	visitContentReqeust.Data.PosterHang = getPOSMStatus(cursor.getInt(posterIndex)); //海报及吊旗悬挂:齐, 缺,破损,不允许
			    	visitContentReqeust.Data.SinglePage = getPOSMStatus(cursor.getInt(pageIndex)); //单页:齐, 缺,破损,不允许
			    	visitContentReqeust.Data.StandPileHead = getPOSMStatus(cursor.getInt(standIndex)); //X展架及堆头布置:齐, 缺,破损,不允许
			    	visitContentReqeust.Data.ExceptionDetails = cursor.getString(errorIndex);  //异常详情
			    	String title1 = cursor.getString(backupText1Index);
			    	if(title1 != null && title1.length() > 0){
			    		if(visitContentReqeust.Data.PosmBackups == null){
			    			visitContentReqeust.Data.PosmBackups = new ArrayList<SyncModel.DataVisitContentSpecial>();	
			    		}
			    		SyncModel.DataVisitContentSpecial backupA = new SyncModel.DataVisitContentSpecial();
			    		backupA.Title = title1;
			    		backupA.Value = cursor.getString(backup1Index);
			    		visitContentReqeust.Data.PosmBackups.add(backupA);
			    	}
			    	String title2 = cursor.getString(backupText2Index);
			    	if(title2 != null && title2.length() > 0){
			    		if(visitContentReqeust.Data.PosmBackups == null){
			    			visitContentReqeust.Data.PosmBackups = new ArrayList<SyncModel.DataVisitContentSpecial>();	
			    		}
			    		SyncModel.DataVisitContentSpecial backupB = new SyncModel.DataVisitContentSpecial();
			    		backupB.Title = title2;
			    		backupB.Value = cursor.getString(backup2Index);
			    		visitContentReqeust.Data.PosmBackups.add(backupB);
			    	}
			    }
			}
		}catch(Exception e){
			e.printStackTrace();
			Log.e("getSalesData error");
		}finally{
			if(cursor != null){
				cursor.close();
				cursor = null;
			}
		}
	}

	/**
	 * 获取竞品数据
	 */
	private void getCompeteData(){
		Cursor cursor = mContext.getContentResolver().query(StoresManagerSettings.SupervisorStoreCompeteColumns.CONTENT_URI_NO_NOTIFICATION, null,
				mWhere, null, null);
		try {
			//数据库数据index
			final int storeIdIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStoreCompeteColumns.STOREID);
			final int brandIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStoreCompeteColumns.COMPETE_BRANDNAME);
			final int modelIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStoreCompeteColumns.COMPETE_MODELNAME);
			final int priceIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStoreCompeteColumns.COMPETE_PRICE);
			final int sellcountIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStoreCompeteColumns.COMPETE_SELLCOUNT);
			final int datanameIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStoreCompeteColumns.COMPETE_DATANAMES);
			final int otherIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStoreCompeteColumns.COMPETE_OTHERS);
			final int photoIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStoreCompeteColumns.COMPETE_PHOTO);
			final int typeIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStoreCompeteColumns.COMPETE_TYPE);
		
			while (cursor.moveToNext()) { //遍历所有数据
				//出样数据信息
				String storeId = cursor.getString(storeIdIndex);
			    int visitId = getVisitId(storeId);
			    if(visitId != -1){
			    	SyncModel.VisitContentReqeust visitContentReqeust = getVisitContentReqeust(visitId);
			    	int type = cursor.getInt(typeIndex);
			    	if(type == SvStoreCompeteActivity.TYPE_COMPETE_CONTENT_PRICE){ //竞品价格
			    		if(visitContentReqeust.CompPrices == null){
				    		visitContentReqeust.CompPrices = new ArrayList<DataVisitContentCompetitor>();
				    	}
			    		SyncModel.DataVisitContentCompetitor comprice = new SyncModel.DataVisitContentCompetitor();
			    		comprice.Brands = cursor.getString(brandIndex);
			    		comprice.Model = cursor.getString(modelIndex);
			    		comprice.Price = cursor.getDouble(priceIndex);
			    		visitContentReqeust.CompPrices.add(comprice);
			    	}else if(type == SvStoreCompeteActivity.TYPE_COMPETE_CONTENT_FUCTION){ //新品功能
			    		if(visitContentReqeust.CompNews == null){
				    		visitContentReqeust.CompNews = new ArrayList<DataVisitContentCompetitor>();
				    	}
			    		SyncModel.DataVisitContentCompetitor compnew = new SyncModel.DataVisitContentCompetitor();
			    		compnew.Brands = cursor.getString(brandIndex);
			    		compnew.Model = cursor.getString(modelIndex);
			    		compnew.Price = cursor.getDouble(priceIndex);
			    		compnew.Function = cursor.getString(datanameIndex);
			    		compnew.OtherFunction = cursor.getString(otherIndex);
			    		compnew.Photo = getBase64CoderData(cursor.getBlob(photoIndex));
			    		visitContentReqeust.CompNews.add(compnew);
			    	}else if(type == SvStoreCompeteActivity.TYPE_COMPETE_CONTENT_ACTIVITY){ //竞品活动
			    		if(visitContentReqeust.CompPromotions == null){
				    		visitContentReqeust.CompPromotions = new ArrayList<DataVisitContentCompetitor>();
				    	}
			    		SyncModel.DataVisitContentCompetitor promotion = new SyncModel.DataVisitContentCompetitor();
			    		promotion.Brands = cursor.getString(brandIndex);
			    		promotion.Model = cursor.getString(modelIndex);
			    		promotion.Price = cursor.getDouble(priceIndex);;
			    		promotion.SaleNum = cursor.getInt(sellcountIndex);;
			    		promotion.Activity = cursor.getString(datanameIndex);
			    		promotion.OtherActivity = cursor.getString(otherIndex);
			    		promotion.Photo = getBase64CoderData(cursor.getBlob(photoIndex));
			    		visitContentReqeust.CompPromotions.add(promotion);
			    	}
			    }
			}
		}catch(Exception e){
			e.printStackTrace();
			Log.e("getPOSMData error");
		}finally{
			if(cursor != null){
				cursor.close();
				cursor = null;
			}
		}
	}

	/**
	 * 获取促销员信息数据
	 */
	private void getPromoterInfoData(){
		Cursor cursor = mContext.getContentResolver().query(StoresManagerSettings.SupervisorStorePromoterColumns.CONTENT_URI_NO_NOTIFICATION, null,
				mWhere, null, null);
		try {
			//获取数据index
			final int storeIdIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePromoterColumns.STOREID);
	        final int pidIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePromoterColumns.PROMOTER_ID);
	        final int pnameIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePromoterColumns.PROMOTER_NAME);
	        final int inpostIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePromoterColumns.PROMOTER_INPOST);
	        final int imageIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePromoterColumns.PROMOTER_IMAGE);
	        final int statusIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePromoterColumns.PROMOTER_STATUS);
	        final int badReasonIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePromoterColumns.PROMOTER_BADREASON);
	        final int checkIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePromoterColumns.PROMOTER_CHECK);
	        final int tmpInfoIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePromoterColumns.PROMOTER_TMPINFO);
	        final int tmpNameIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePromoterColumns.PROMOTER_TMPNAME);
	        final int tmpTelIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePromoterColumns.PROMOTER_TMPTEL);
	        final int notPostReasonIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePromoterColumns.PROMOTER_NOTPOSTREASON);
	        final int problemIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePromoterColumns.PROMOTER_PROBLEM);
	        final int photoIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorStorePromoterColumns.PROMOTER_PHOTO);
		
			while (cursor.moveToNext()) { //遍历所有数据
				//出样数据信息
				String storeId = cursor.getString(storeIdIndex);
			    int visitId = getVisitId(storeId);
			    if(visitId != -1){
			    	SyncModel.VisitContentReqeust visitContentReqeust = getVisitContentReqeust(visitId);
			    	if(visitContentReqeust.Promoters == null){
			    		visitContentReqeust.Promoters = new ArrayList<SyncModel.DataVisitContentPromoter>();    //促销员信息	
			    	}
			    	SyncModel.DataVisitContentPromoter promoterA = new SyncModel.DataVisitContentPromoter();
			    	promoterA.PromoterCode = cursor.getString(pidIndex);
			        promoterA.PromoterName = cursor.getString(pnameIndex);
			        promoterA.DutyStatus = getDutyStatus(cursor.getInt(inpostIndex)); //在岗情况:是/否/休
			        promoterA.Appearance = getAppearance(cursor.getInt(imageIndex)); //促销员形象:好/较好/差
			        promoterA.Performance = getPerformance(cursor.getInt(statusIndex)); //促销员状态:好/不好
			        promoterA.NotGoodReason = cursor.getString(badReasonIndex); //不好原因
			        promoterA.Attendance = getAttendance(cursor.getInt(checkIndex));          //促销员考勤:全勤/病假/事假/休/产
			        promoterA.TemporaryPromoter = getTemporaryPromoter(cursor.getInt(tmpInfoIndex)) ;   //临促情况:是/否/无（选择是或否需填写：临促姓名/电话/不在岗原因，文字框）
			        promoterA.TempName = cursor.getString(tmpNameIndex);           //临促姓名
			        promoterA.TempMobile = cursor.getString(tmpTelIndex);;          //电话
			        promoterA.OffDutyReason = cursor.getString(notPostReasonIndex);;       //不在岗原因
			        promoterA.Question = cursor.getString(problemIndex);;             //促销员问题
			        promoterA.Photo = getBase64CoderData(cursor.getBlob(photoIndex)); //促销员照片（非必拍）
			        visitContentReqeust.Promoters.add(promoterA);
			    }
			}
		}catch(Exception e){
			e.printStackTrace();
			Log.e("getPromoterInfoData error");
		}finally{
			if(cursor != null){
				cursor.close();
				cursor = null;
			}
		}
	}

	/**
	 * 获取特殊任务数据
	 */
	private void getSpecialTaskData(){
		Cursor cursor = mContext.getContentResolver().query(StoresManagerSettings.SpecialTaskColumns.CONTENT_URI_NO_NOTIFICATION, null,
				mWhere, null, null);
		try {
			//获取数据index
			final int storeIdIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SpecialTaskColumns.STOREID);
            final int taskdesIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SpecialTaskColumns.TASK_DES);
            final int taskfdIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SpecialTaskColumns.TASK_FEEDBACK);
            while (cursor.moveToNext()) {
            	String storeId = cursor.getString(storeIdIndex);
			    int visitId = getVisitId(storeId);
			    if(visitId != -1){
			    	SyncModel.VisitContentReqeust visitContentReqeust = getVisitContentReqeust(visitId);
			    	if(visitContentReqeust.Data.Specials == null){
			    		visitContentReqeust.Data.Specials = new ArrayList<SyncModel.DataVisitContentSpecial>(); //促销员信息	
			    	}
			    	SyncModel.DataVisitContentSpecial specialA = new SyncModel.DataVisitContentSpecial();
			    	specialA.Title = cursor.getString(taskdesIndex);
			    	specialA.Value = cursor.getString(taskfdIndex);
			    	visitContentReqeust.Data.Specials.add(specialA);
			    }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("getSpecialTaskData error");
        } finally {
        	if(cursor != null){
        		cursor.close();
        		cursor = null;
        	}
        }
	}

	/**
	 * 更具拜访ID查找拜访内容
	 */
	private SyncModel.VisitContentReqeust getVisitContentReqeust(int visitId){
		for(SyncModel.VisitContentReqeust result : mVisitContentList){ //遍历 存在则返回
			if(result.VisitId == visitId){
				return result;
			}
		}
		//遍历没有则新建
		SyncModel.VisitContentReqeust vcresult = new SyncModel.VisitContentReqeust();
		vcresult.VisitId = visitId;
		vcresult.Uuid = DataUtils.mUserData.mUuid;
		vcresult.Data = new SyncModel.VisitContentReqData();
		mVisitContentList.add(vcresult);
		return vcresult;
	}

	/**
	 * 更具门店ID获取拜访ID
	 * @return visitId
	 */
	private int getVisitId(String storeId){
		for(VisitItem item : mVisitList){
			if(item.mStoreId.equals(storeId)){
				return item.visitId;
			}
		}
		return -1;
	}

    /**
     * 获取展台破损是否完工
     * @param id选中项ID索引
     */
	public String getBoothsBreakageStatus(int id){
		String text = null;
		if(id == 1){ //是
			text = mContext.getString(R.string.dialog_yes);
		}else if(id == 0){ //否
			text = mContext.getString(R.string.dialog_no);
		}
		return text;
	}

	/**
	 * 在岗情况
	 * @param id选中项ID索引
	 */
	public String getDutyStatus(int id){
		String text = null;
		if(id == 0){ //是
			text = mContext.getString(R.string.dialog_yes);
		}else if(id == 1){ //否
			text = mContext.getString(R.string.dialog_no);
		}else if(id == 2){ //休
			text = mContext.getString(R.string.promoter_select_xiu);
		}
		return text;
	}

	/**
	 * 形象
	 * @param id选中项ID索引
	 */
	public String getAppearance(int id){
		String text = null;
		if(id == 0){ //好
			text = mContext.getString(R.string.promoter_select_hao);
		}else if(id == 1){ //较好
			text = mContext.getString(R.string.promoter_select_jiaohao);
		}else if(id == 2){ //差
			text = mContext.getString(R.string.promoter_select_cha);
		}
		return text;
	}

	/**
	 * 状态
	 * @param id选中项ID索引
	 */
	public String getPerformance(int id){
		String text = null;
		if(id == 0){ //好
			text = mContext.getString(R.string.promoter_select_hao);
		}else if(id == 1){ //不好
			text = mContext.getString(R.string.promoter_select_buhao);
		}
		return text;
	}

	/**
	 * 考勤
	 * @param id选中项ID索引
	 */
	public String getAttendance(int id){
		String text = null;
		if(id == 0){ //全勤
			text = mContext.getString(R.string.promoter_select_quanqin);
		}else if(id == 1){ //病假
			text = mContext.getString(R.string.promoter_select_bingjia);
		}else if(id == 2){ //事假
			text = mContext.getString(R.string.promoter_select_shijia);
		}else if(id == 3){ //休
			text = mContext.getString(R.string.promoter_select_xiu);
		}else if(id == 4){ //产假
			text = mContext.getString(R.string.promoter_select_chan);
		}
		return text;
	}

	/**
	 * 临促情况
	 * @param id选中项ID索引
	 */
	public String getTemporaryPromoter(int id){
		String text = null;
		if(id == 0){ //是
			text = mContext.getString(R.string.dialog_yes);
		}else if(id == 1){ //否
			text = mContext.getString(R.string.dialog_no);
		}else if(id == 2){ //无
			text = mContext.getString(R.string.promoter_select_wu);
		}
		return text;
	}
	/**
     * 获取充足和缺乏
     * @param id选中项ID索引
     */
	public String getStockStatus(int id){
		String text = null;
		if(id == 0){ //充足
			text = mContext.getString(R.string.stock_enough);
		}else if(id == 1){ //缺乏
			text = mContext.getString(R.string.stock_shortage);
		}
		return text;
	}
	/**
     * 获取齐, 缺,破损,不允许
     * @param id选中项ID索引
     * 
     */
	public String getPOSMStatus(int id){
		String text = null;
		if(id == 0){ //齐
			text = mContext.getString(R.string.posm_status_1);
		}else if(id == 1){ //缺
			text = mContext.getString(R.string.posm_status_2);
		}else if(id == 2){ //破损
			text = mContext.getString(R.string.posm_status_3);
		}else if(id == 3){ //不允许
			text = mContext.getString(R.string.posm_status_4);
		}
		return text;
	}
	/**
	 * 获取型号列表数据
	 */
	private List<String> getModelsList(String models){
		if(models != null && models.length() > 0){
			String[] modelArr = models.split(SalesData.SPLIT_MORE);
			List<String> list = new ArrayList<String>(modelArr.length);
			Collections.addAll(list, modelArr);
			return list;
		}
		return null;
	}

	/**
	 * 获取转码数据
	 * @param data 数据
	 */
	private String getBase64CoderData(byte[] data){
		if(data != null && data.length > 1){
			return new String(Base64Coder.encode(data));
		}
		return null;
	}
	/**
	 * 获取数据
	 */
	private Date getData(long time){
		if(time > 0){
			return new Date(time);
		}
		return null;
	}

    /**
     * 获取指定拜访信息
     * @param index
     */
    public String getPutVisitCheckContent(int index){
    	String result = null;
    	if(mVisitCheckRequestList != null && mVisitCheckRequestList.size() > 0){
    		try {
              result = HttpUtil.getObjectMapper().writeValueAsString(mVisitCheckRequestList.get(index));
          } catch (Exception e) {
              e.printStackTrace();
          }
    	}
        Log.d(index + "===getPutVisitCheckContent=" + result);
        return result;
    }

    /**
     * 获取签到数据大小
     */
    public int getVisitCheckSize(){
    	if(mVisitCheckRequestList != null){
    		Log.d("VisitChecksize=" + mVisitCheckRequestList.size());
    		return mVisitCheckRequestList.size();
    	}
    	return 0;
    }

    /**
     * 获拜访内容大小
     */
    public int getVisitContentSize(){
    	if(mVisitContentList != null){
    		Log.d("VisitContentList=" + mVisitContentList.size());
    		return mVisitContentList.size();
    	}
    	return 0;
    }

    /**
     * 获取指定index拜访内容信息
     * @param index
     */
    public String getPutVisitContent(int index){
    	String result = null;
    	if(mVisitContentList != null && mVisitContentList.size() > 0){
    		try {
              result = HttpUtil.getObjectMapper().writeValueAsString(mVisitContentList.get(index));
          } catch (Exception e) {
              e.printStackTrace();
          }
    	}
        Log.d(index + "===getPutVisitContent=" + result);
        return result;
    }

    /**
     * 设置数据成功上报 避免同步重复上报
     */
    public void savePutSuccess(){
		ContentValues values = new ContentValues();
		for(VisitItem item : mVisitList){ //遍历所有数据
			values.clear();
			values.put(StoresManagerSettings.SupervisorVisitTaskColumns.PUTSTATUS, 1); //标志上报成功
			String where = StoresManagerSettings.SupervisorVisitTaskColumns.VISITID +"=" + item.visitId;
			mContext.getContentResolver().update(StoresManagerSettings.SupervisorVisitTaskColumns.CONTENT_URI_NO_NOTIFICATION, values, where, null);
		}
    }

    class VisitItem{
    	public int visitId;
    	public String mStoreId;
    }

    /**
     * 更新已上传数据 设置为历史数据
     */
    public void updatePutedData(){
    	if(mWhere.length() > 1){
    		ContentValues values = new ContentValues();
        	values.put(StoresManagerSettings.SAVED, 1); //设置保存的数据
            mContext.getContentResolver().update(StoresManagerSettings.SpecialTaskColumns.CONTENT_URI_NO_NOTIFICATION, values, mWhere, null);
            mContext.getContentResolver().update(StoresManagerSettings.SupervisorStorePOSMColumns.CONTENT_URI_NO_NOTIFICATION, values, mWhere, null);
            mContext.getContentResolver().update(StoresManagerSettings.SupervisorStoreCompeteColumns.CONTENT_URI_NO_NOTIFICATION, values, mWhere, null);
            mContext.getContentResolver().update(StoresManagerSettings.SupervisorStoreCompeteSelectedColumns.CONTENT_URI_NO_NOTIFICATION, values, mWhere, null);
            mContext.getContentResolver().update(StoresManagerSettings.SupervisorStoreSalesColumns.CONTENT_URI_NO_NOTIFICATION, values, mWhere, null);
            mContext.getContentResolver().update(StoresManagerSettings.SupervisorStoreBoothColumns.CONTENT_URI_NO_NOTIFICATION, values, mWhere, null);
            mContext.getContentResolver().update(StoresManagerSettings.SupervisorStoreSampleColumns.CONTENT_URI_NO_NOTIFICATION, values, mWhere, null);
            mContext.getContentResolver().update(StoresManagerSettings.SupervisorStorePromoterColumns.CONTENT_URI_NO_NOTIFICATION, values, mWhere, null);
    	}
    }

    /**
     * 清除缓存
     */
    public static void clearCacheData(Context context){
    	String where = StoresManagerSettings.SAVED + "=1";
    	context.getContentResolver().delete(StoresManagerSettings.SpecialTaskColumns.CONTENT_URI_NO_NOTIFICATION, where, null);
    	context.getContentResolver().delete(StoresManagerSettings.SupervisorStorePOSMColumns.CONTENT_URI_NO_NOTIFICATION, where, null);
    	context.getContentResolver().delete(StoresManagerSettings.SupervisorStoreCompeteColumns.CONTENT_URI_NO_NOTIFICATION, where, null);
    	context.getContentResolver().delete(StoresManagerSettings.SupervisorStoreCompeteSelectedColumns.CONTENT_URI_NO_NOTIFICATION, where, null);
    	context.getContentResolver().delete(StoresManagerSettings.SupervisorStoreSalesColumns.CONTENT_URI_NO_NOTIFICATION, where, null);
    	context.getContentResolver().delete(StoresManagerSettings.SupervisorStoreBoothColumns.CONTENT_URI_NO_NOTIFICATION, where, null);
    	context.getContentResolver().delete(StoresManagerSettings.SupervisorStoreSampleColumns.CONTENT_URI_NO_NOTIFICATION, where, null);
    	context.getContentResolver().delete(StoresManagerSettings.SupervisorStorePromoterColumns.CONTENT_URI_NO_NOTIFICATION, where, null);
    }
}
